package org.yjc.controller;

import java.util.HashMap;
import java.util.HashSet;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.yjc.custom.DatagridUtils;
import org.yjc.custom.JournalUtils;
import org.yjc.custom.UserUtils;
import org.yjc.entity.College;
import org.yjc.entity.Student;
import org.yjc.entity.SysRole;
import org.yjc.entity.SysUser;
import org.yjc.entity.TbClass;
import org.yjc.form.StudentForm;
import org.yjc.repository.SysRoleRepository;
import org.yjc.repository.SysUserRepository;
import org.yjc.service.StudentService;
import org.yjc.service.SysUserService;
import org.yjc.service.TbClassService;

@Controller
@RequestMapping(value="/student")
public class StudentController {
	@Autowired
	private StudentService studentservice;
	@Autowired
	private TbClassService tbclassserivce;
	@Autowired
	SysRoleRepository roleDAO;
	@Autowired
	private UserUtils userutils;
	@Autowired
	private JournalUtils journalutils;
	@Autowired
	private SysUserService sysuserservice;
	
	@RequestMapping(value="/studentmain")
	public String studentmain(ModelMap map) {
		List<TbClass> tbclass = tbclassserivce.findAll();
		map.put("tbclass",tbclass);
		return "student/studentmain";
	}
	
	@RequestMapping(value="/list")
	@ResponseBody
	public Object list(DatagridUtils param,String name,String stuNum,String age,String tbclassid) {
		Pageable pageable = param.buildPageable();
		Page<Student> page = null;
		//安全查询
		Specification<Student> spec = new Specification<Student>() {
			@Override
			public Predicate toPredicate(Root<Student> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
				HashSet<Predicate> rules = new HashSet<>();
				if(StringUtils.hasText(name)) {
					rules.add(criteriaBuilder.like(root.get("name"), "%"+name+"%"));
				}else if(StringUtils.hasText(stuNum)) {
					rules.add(criteriaBuilder.like(root.get("stuNum"), "%"+stuNum+"%"));
				}else if(StringUtils.hasText(age)) {
					rules.add(criteriaBuilder.like(root.get("age"), "%"+age+"%"));
				}
				rules.add(criteriaBuilder.equal(root.get("tbclass").get("id"),tbclassid));
				return criteriaBuilder.and(rules.toArray(new Predicate[rules.size()]));
			}
		};
		page = studentservice.findAll(spec,pageable);
		HashMap<String, Object> result = DatagridUtils.biuldDatagridResult(page);
		return result;
	}
	
	@RequestMapping(value="/save")
	@ResponseBody
	public String save(StudentForm form,Integer tbclassid) {
		BCryptPasswordEncoder encoder=new BCryptPasswordEncoder(); //密码加密器
		Student student = new Student();
		SysUser sysuser = userutils.getUser(); //获取到当前用户
		if(form.getId()!=null) {
			student = studentservice.findById(form.getId());
			student.setId(form.getId());
			BeanUtils.copyProperties(form, student);
			//录入日志
			journalutils.journal1("修改学生信息",sysuser.getName()+"进行了修改学生信息操作");
		}else {
			BeanUtils.copyProperties(form, student,"id");
			journalutils.journal1("添加学生",sysuser.getName()+"添加了"+"("+form.getName()+")");
		}
		student.setPassword(encoder.encode("111111")); //把密码进行加密
		student.setTbclass(tbclassserivce.findById(tbclassid)); //存入班级
		SysRole role = roleDAO.findById(2).get(); //给权限
		student.getRoles().add(role);
		studentservice.save(student);
		return "OK";
	}
	
	@RequestMapping(value="/delete")
	@ResponseBody
	public String delete(String ids) {
		SysUser sysuser = userutils.getUser();
		String[] ids1 = ids.split(",");//去除“，” 将多个id存入数组中
		for(int i = 0;i<ids1.length;i++) {
			Student student = studentservice.findById(Integer.parseInt(ids1[i]));
			studentservice.deleteById(Integer.parseInt(ids1[i]));
			//日志
			journalutils.journal1("删除学生",sysuser.getName()+"删除了"+"("+student.getName()+")");
		}
		return "OK";
	}
	
	@RequestMapping(value="/reload")
	@ResponseBody
	public String reload(String ids) {
		SysUser sysuser = userutils.getUser();
		BCryptPasswordEncoder encoder=new BCryptPasswordEncoder(); //密码加密器
		String[] ids1 = ids.split(",");//去除“，” 将多个id存入数组中
		for(int i = 0;i<ids1.length;i++) {
			Student student = studentservice.findById(Integer.parseInt(ids1[i]));
			student.setPassword(encoder.encode("111111"));
			studentservice.save(student);
			//日志
			journalutils.journal1("重置学生密码",sysuser.getName()+"重置了"+"("+student.getName()+")的密码");
		}
		return "OK";
	}
	
	@RequestMapping(value="/message")
	public String message(ModelMap map) {
		Integer id = userutils.getUser().getId();
		Student student = studentservice.findById(id);
		SysRole role = roleDAO.findById(2).get(); //给权限
		map.put("role", role);
		map.put("student", student);
		return "student/message";
	}
}
